import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/bottom_sheet.dart';
import 'package:hj_crm/utils/form_photo.dart';
import 'package:hj_crm/utils/form_utils.dart';
import 'package:hj_crm/utils/image_utils.dart';
import 'package:hj_crm/utils/toast_utils.dart';

/// 用户表单
class UserFormWidget extends StatefulWidget {
  final String? uId;

  const UserFormWidget({super.key, this.uId});

  @override
  State<UserFormWidget> createState() => _UserFormWidgetState();
}

class _UserFormWidgetState extends State<UserFormWidget> {
  RequestRepository repository = Get.find<RequestRepository>();
  final _formKey = GlobalKey<FormBuilderState>();

  String? avatarPath;

  bool isPhysicalExam = false; // 是否体检
  bool operationFlag = false; // 是否做过手术

  late TextEditingController _nameController;
  late TextEditingController _phoneController;
  late TextEditingController _idCardController;
  late TextEditingController _birthDateController;
  late TextEditingController _genderController;
  late TextEditingController _ageController;
  late TextEditingController _addressController;
  late TextEditingController _wechatIdController;
  late TextEditingController _workUnitController;
  late TextEditingController _unitNatureController;
  late TextEditingController _incomeRangeController;
  late TextEditingController _healthStatusController;
  late TextEditingController _characterTraitController;
  late TextEditingController _familyMemberController;
  late TextEditingController _emergencyContactController;
  late TextEditingController _emergencyPhoneController;
  late TextEditingController _serviceCommissionerController;
  late TextEditingController _customerSourceController;
  late TextEditingController _surgeryController;
  late TextEditingController _medicationController;
  late TextEditingController _noteController;

  late FocusNode _nameFocusNode;
  late FocusNode _phoneFocusNode;
  late FocusNode _idCardFocusNode;
  late FocusNode _birthDateFocusNode;
  late FocusNode _genderFocusNode;
  late FocusNode _ageFocusNode;
  late FocusNode _addressFocusNode;
  late FocusNode _wechatIdFocusNode;
  late FocusNode _workUnitFocusNode;
  late FocusNode _unitNatureFocusNode;
  late FocusNode _incomeRangeFocusNode;
  late FocusNode _healthStatusFocusNode;
  late FocusNode _characterTraitFocusNode;
  late FocusNode _familyMemberFocusNode;
  late FocusNode _emergencyContactFocusNode;
  late FocusNode _emergencyPhoneFocusNode;
  late FocusNode _serviceCommissionerFocusNode;
  late FocusNode _customerSourceFocusNode;
  late FocusNode _surgeryFocusNode;
  late FocusNode _medicationFocusNode;
  late FocusNode _noteFocusNode;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _phoneController = TextEditingController();
    _idCardController = TextEditingController();
    _birthDateController = TextEditingController();
    _genderController = TextEditingController();
    _ageController = TextEditingController();
    _addressController = TextEditingController();
    _wechatIdController = TextEditingController();
    _workUnitController = TextEditingController();
    _unitNatureController = TextEditingController();
    _incomeRangeController = TextEditingController();
    _healthStatusController = TextEditingController();
    _characterTraitController = TextEditingController();
    _familyMemberController = TextEditingController();
    _emergencyContactController = TextEditingController();
    _emergencyPhoneController = TextEditingController();
    _serviceCommissionerController = TextEditingController();
    _customerSourceController = TextEditingController();
    _surgeryController = TextEditingController();
    _medicationController = TextEditingController();
    _noteController = TextEditingController();

    _nameFocusNode = FocusNode();
    _phoneFocusNode = FocusNode();
    _idCardFocusNode = FocusNode();
    _birthDateFocusNode = FocusNode();
    _genderFocusNode = FocusNode();
    _ageFocusNode = FocusNode();
    _addressFocusNode = FocusNode();
    _wechatIdFocusNode = FocusNode();
    _workUnitFocusNode = FocusNode();
    _unitNatureFocusNode = FocusNode();
    _incomeRangeFocusNode = FocusNode();
    _healthStatusFocusNode = FocusNode();
    _characterTraitFocusNode = FocusNode();
    _familyMemberFocusNode = FocusNode();
    _emergencyContactFocusNode = FocusNode();
    _emergencyPhoneFocusNode = FocusNode();
    _serviceCommissionerFocusNode = FocusNode();
    _customerSourceFocusNode = FocusNode();
    _surgeryFocusNode = FocusNode();
    _medicationFocusNode = FocusNode();
    _noteFocusNode = FocusNode();

    if (widget.uId != null) {
      repository.findUserInfo(
          id: widget.uId!,
          success: (data) {
            avatarPath = data.userPhoto;
            _nameController.text = data.name ?? '';
            _phoneController.text = data.phoneNumber ?? '';
            _idCardController.text = data.idCard ?? '';
            _birthDateController.text = data.birthDate ?? '';
            _genderController.text = data.gender == 1 ? '男' : '女';
            _ageController.text = data.age.toString();
            _addressController.text = data.address ?? '';
            _wechatIdController.text = data.wechatId ?? '';
            _workUnitController.text = data.workUnit ?? '';
            _unitNatureController.text = data.unitProperty ?? '';
            _incomeRangeController.text = data.incomeRange ?? '';
            _healthStatusController.text = data.healthStatus ?? '';
            _characterTraitController.text = data.characterTrait ?? '';
            _familyMemberController.text = data.childrenSituation ?? '';
            _emergencyContactController.text = data.exigencyUser ?? '';
            _emergencyPhoneController.text = data.exigencyMobile ?? '';
            _serviceCommissionerController.text = data.serviceSpecialist ?? '';
            _customerSourceController.text = data.sourceUser ?? '';
            isPhysicalExam = data.isPhysicalExam ?? false;
            operationFlag = data.operationFlag ?? false;
            _surgeryController.text = data.operationName ?? '';
            _medicationController.text = data.medicine ?? '';
            _noteController.text = data.note ?? '';
            // setState(() {});

            _formKey.currentState?.patchValue({
              'isPhysicalExam': isPhysicalExam, // 设置新的值
              'operationFlag': operationFlag, // 设置新的值
            });
          });
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _idCardController.dispose();
    _birthDateController.dispose();
    _genderController.dispose();
    _ageController.dispose();
    _addressController.dispose();
    _wechatIdController.dispose();
    _workUnitController.dispose();
    _unitNatureController.dispose();
    _incomeRangeController.dispose();
    _healthStatusController.dispose();
    _characterTraitController.dispose();
    _familyMemberController.dispose();
    _emergencyContactController.dispose();
    _emergencyPhoneController.dispose();
    _serviceCommissionerController.dispose();
    _customerSourceController.dispose();
    _surgeryController.dispose();
    _medicationController.dispose();
    _noteController.dispose();

    _nameFocusNode.dispose();
    _phoneFocusNode.dispose();
    _idCardFocusNode.dispose();
    _birthDateFocusNode.dispose();
    _genderFocusNode.dispose();
    _ageFocusNode.dispose();
    _addressFocusNode.dispose();
    _wechatIdFocusNode.dispose();
    _workUnitFocusNode.dispose();
    _unitNatureFocusNode.dispose();
    _incomeRangeFocusNode.dispose();
    _healthStatusFocusNode.dispose();
    _characterTraitFocusNode.dispose();
    _familyMemberFocusNode.dispose();
    _emergencyContactFocusNode.dispose();
    _emergencyPhoneFocusNode.dispose();
    _serviceCommissionerFocusNode.dispose();
    _customerSourceFocusNode.dispose();
    _surgeryFocusNode.dispose();
    _noteFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('用户表单'),
        ),
        body: SingleChildScrollView(
          child: FormBuilder(
            key: _formKey,
            autovalidateMode: AutovalidateMode.disabled,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: const Text('用户基本信息',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  ),
                  FormPhotoWidget(
                    path: avatarPath,
                    onTap: () {
                      openImageBottomSheet((index) {
                        ImageUtils.selectImage(
                          kind: index == 0 ? ImageSourceKind.image : ImageSourceKind.camera,
                          result: (bytesData) {
                            repository.imageUpload(
                              bytesData: bytesData,
                              fileName: '${DateTime.now().millisecondsSinceEpoch}.jpg',
                              success: (data) {
                                setState(() {
                                  avatarPath = data.first as String?;
                                });
                              },
                              fail: (code, msg) {
                                ToastUtils.show(msg);
                              },
                            );
                          },
                        );
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'name',
                    decoration: const InputDecoration(labelText: '用户姓名'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入用户姓名'),
                    ]),
                    controller: _nameController,
                    focusNode: _nameFocusNode,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_phoneFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'phoneNumber',
                    decoration: const InputDecoration(labelText: '手机号'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入手机号码'),
                      FormBuilderValidators.numeric(errorText: '手机号码格式不正确'),
                      FormBuilderValidators.minLength(11, errorText: '手机号码格式不正确'),
                      FormBuilderValidators.maxLength(11, errorText: '手机号码格式不正确'),
                    ]),
                    keyboardType: TextInputType.phone,
                    controller: _phoneController,
                    focusNode: _phoneFocusNode,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_idCardFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'idCard',
                    decoration: const InputDecoration(labelText: '身份证号'),
                    keyboardType: TextInputType.number,
                    controller: _idCardController,
                    focusNode: _idCardFocusNode,
                    textInputAction: TextInputAction.next,
                    onSubmitted: (value) {
                      if (value != null) {
                        calculateUserBaseInfo(value, (gender, birthDate, age) {
                          setState(() {
                            _genderController.text = gender;
                            if (birthDate.contains(' ')) {
                              _birthDateController.text = birthDate.split(' ')[0];
                              _ageController.text = age;
                            }
                          });
                        });
                      }
                    },
                    onEditingComplete: () {
                      if (_idCardController.text.length != 18) {
                        FocusScope.of(context).requestFocus(_birthDateFocusNode);
                      } else {
                        FocusScope.of(context).requestFocus(_addressFocusNode);
                      }
                    },
                    onChanged: (newValue) {
                      if (newValue != null) {
                        calculateUserBaseInfo(newValue, (gender, birthDate, age) {
                          setState(() {
                            _genderController.text = gender;
                            if (birthDate.contains(' ')) {
                              _birthDateController.text = birthDate.split(' ')[0];
                              _ageController.text = age;
                            }
                          });
                        });
                      }
                    },
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.numeric(errorText: '身份证号码格式不正确'),
                      FormBuilderValidators.minLength(18, errorText: '身份证号码格式不正确'),
                      FormBuilderValidators.maxLength(18, errorText: '身份证号码格式不正确'),
                    ]),
                  ),
                  FormBuilderTextField(
                    enabled: _idCardController.text.length != 18,
                    readOnly: true,
                    name: 'birthDate',
                    decoration: const InputDecoration(labelText: '出生日期'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请选择出生日期'),
                    ]),
                    controller: _birthDateController,
                    onTap: () {
                      openDatePicker(context, DateItemKind.birthDate, (value) {
                        setState(() {
                          _birthDateController.text = value;
                          _ageController.text = calculateAge(value).toString();
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    enabled: _idCardController.text.length != 18,
                    name: 'gender',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '性别'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请选择性别'),
                    ]),
                    controller: _genderController,
                    onTap: () {
                      openGenderPicker(context, (value) {
                        setState(() {
                          _genderController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    enabled: _birthDateController.text.isEmpty,
                    name: 'age',
                    decoration: const InputDecoration(labelText: '年龄'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入年龄'),
                      FormBuilderValidators.numeric(errorText: '请输入数字'),
                    ]),
                    controller: _ageController,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_addressFocusNode);
                    },
                    keyboardType: TextInputType.number,
                  ),
                  FormBuilderTextField(
                    name: 'address',
                    decoration: const InputDecoration(labelText: '详细地址'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入详细地址'),
                    ]),
                    controller: _addressController,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_wechatIdFocusNode);
                    },
                  ),
                  SizedBox(height: 20),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: const Text('用户个人情况',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  ),
                  FormBuilderTextField(
                    name: 'wechatId',
                    decoration: const InputDecoration(labelText: '微信号'),
                    controller: _wechatIdController,
                    textInputAction: TextInputAction.next,
                    focusNode: _wechatIdFocusNode,
                    keyboardType: TextInputType.name,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_workUnitFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'workUnit',
                    decoration: const InputDecoration(labelText: '工作单位'),
                    controller: _workUnitController,
                    textInputAction: TextInputAction.next,
                    focusNode: _workUnitFocusNode,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  FormBuilderTextField(
                    name: 'unitProperty',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '单位性质'),
                    controller: _unitNatureController,
                    onTap: () {
                      openUnitNaturePicker(context, (value) {
                        setState(() {
                          _unitNatureController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'incomeRange',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '收入范围'),
                    controller: _incomeRangeController,
                    onTap: () {
                      openIncomeRangePicker(context, (value) {
                        setState(() {
                          _incomeRangeController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'healthStatus',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '健康状况'),
                    controller: _healthStatusController,
                    onTap: () {
                      openHealthStatusPicker(context, (value) {
                        setState(() {
                          _healthStatusController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'characterTrait',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '性格特征'),
                    controller: _characterTraitController,
                    onTap: () {
                      openCharacterTraitPicker(context, (value) {
                        setState(() {
                          _characterTraitController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'childrenSituation',
                    decoration: InputDecoration(labelText: '家庭成员情况', hintText: fmMask.hint),
                    controller: _familyMemberController,
                    keyboardType: fmMask.textInputType,
                    inputFormatters: [fmMask.formatter],
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_emergencyContactFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'exigencyUser',
                    decoration: const InputDecoration(labelText: '紧急联系人'),
                    controller: _emergencyContactController,
                    focusNode: _emergencyContactFocusNode,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_emergencyPhoneFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'exigencyMobile',
                    decoration: const InputDecoration(labelText: '紧急联系电话'),
                    controller: _emergencyPhoneController,
                    focusNode: _emergencyPhoneFocusNode,
                    keyboardType: TextInputType.phone,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_serviceCommissionerFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'serviceSpecialist',
                    decoration: const InputDecoration(labelText: '服务专员'),
                    controller: _serviceCommissionerController,
                    focusNode: _serviceCommissionerFocusNode,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  FormBuilderTextField(
                    name: 'sourceUser',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '客户来源'),
                    controller: _customerSourceController,
                    onTap: () {
                      openCustomerSourcePicker(context, (value) {
                        setState(() {
                          _customerSourceController.text = value;
                        });
                      });
                    },
                  ),
                  FormBuilderSwitch(
                    name: 'isPhysicalExam',
                    initialValue: isPhysicalExam,
                    selected: isPhysicalExam,
                    title: Text('是否体检'),
                    onChanged: (value) {
                      isPhysicalExam = value ?? false;
                    },
                  ),
                  FormBuilderSwitch(
                    name: 'operationFlag',
                    initialValue: operationFlag,
                    selected: operationFlag,
                    title: Text('是否做过手术'),
                    onChanged: (value) {
                      setState(() {
                        operationFlag = value ?? false;
                      });
                    },
                  ),
                  if (operationFlag)
                    FormBuilderTextField(
                      name: 'operationName',
                      decoration: const InputDecoration(labelText: '做过的手术名称'),
                      controller: _surgeryController,
                      textInputAction: TextInputAction.next,
                      onEditingComplete: () {
                        FocusScope.of(context).requestFocus(_medicationFocusNode);
                      },
                    ),
                  FormBuilderTextField(
                    name: 'medicine',
                    decoration: const InputDecoration(labelText: '服用过的药物'),
                    controller: _medicationController,
                    focusNode: _medicationFocusNode,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_noteFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'note',
                    decoration: const InputDecoration(labelText: '备注'),
                    controller: _noteController,
                    focusNode: _noteFocusNode,
                    textInputAction: TextInputAction.done,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      /// 验证表单
                      if (!_formKey.currentState!.saveAndValidate()) {
                        return;
                      }

                      /// 提交数据
                      Map<String, dynamic> map = {
                        "id": widget.uId ?? '',
                        "name": _nameController.text,
                        "phoneNumber": _phoneController.text,
                        "idCard": _idCardController.text,
                        "birthDate": _birthDateController.text,
                        "gender": _genderController.text == '男' ? 0 : 1,
                        "age": int.tryParse(_ageController.text) ?? 0,
                        "address": _addressController.text,
                        "wechatId": _wechatIdController.text,
                        "workUnit": _workUnitController.text,
                        "unitProperty": _unitNatureController.text,
                        "incomeRange": _incomeRangeController.text,
                        "healthStatus": _healthStatusController.text,
                        "characterTrait": _characterTraitController.text,
                        "childrenSituation": _familyMemberController.text,
                        "exigencyUser": _emergencyContactController.text,
                        "exigencyMobile": _emergencyPhoneController.text,
                        "serviceSpecialist": _serviceCommissionerController.text,
                        "sourceUser": _customerSourceController.text,
                        "isPhysicalExam": isPhysicalExam,
                        "operationFlag": operationFlag,
                        "operationName": _surgeryController.text,
                        "medicine": _medicationController.text,
                        "note": _noteController.text,
                        "userPhoto": avatarPath ?? '',
                      };

                      if (widget.uId == null || widget.uId == '') {
                        repository.addUser(
                          params: map,
                          success: (data) {
                            Navigator.pop(context, true);
                          },
                          fail: (code, msg) {},
                        );
                        return;
                      } else {
                        repository.updateUser(
                            params: map,
                            success: (data) {
                              Navigator.pop(context, true);
                            },
                            fail: (code, msg) {});
                        return;
                      }
                    },
                    child: const Text('保存'),
                  ),
                  SizedBox(height: 10),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
